<template>
    <div class="change-task-edit-view">

      <el-row>
        <el-form ref="form" :inline="true" :model="data" :rules="rules" class="demo-form-inline" label-width="120px" size="medium" label-position="left">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="task_name">
              <el-input v-if="data.isAdd" v-model="data.task_name" placeholder="请输入任务名称" clearable></el-input>
              <span v-else>{{data.task_name}}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="父任务" v-if="data.level != 1">
              <el-select v-model="data.parent_id" @change="planChange" placeholder="请选择父任务" v-if="data.isAdd">
                <el-option
                  v-for="item in planList"
                  :key="item.id"
                  :label="item.task_name"
                  :value="item.id">
                </el-option>
              </el-select>

              <span v-else>{{data.parent_name}}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="前置任务" v-if="data.level != 1">
              <el-select v-model="data.foreground_task_id" @change="preChange" placeholder="请选择前置任务" v-if="data.isAdd" clearable>
                <el-option
                  v-for="item in planList2"
                  :key="item.id"
                  :label="item.task_name"
                  :value="item.id">
                </el-option>
              </el-select>
              <span v-else>{{data.foreground_task_name?data.foreground_task_name:'无'}}</span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="计划开始时间" prop="startDate">
              <el-date-picker
                @change="startchange"
                v-model="data.startDate"
                type="date"
                :editable="false"
                :clearable="false"
                placeholder="选择开始时间"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="计划结束时间" prop="endDate">
              <el-date-picker
                @change="endchange"
                v-model="data.endDate"
                type="date"
                :editable="false"
                :clearable="false"
                placeholder="选择结束时间"
                :picker-options="pickerOptions2">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工期（天）" prop="duration">
              <el-input v-model="data.duration" @keyup.native="durationProving" @blur="blur"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="任务负责人" prop="person_id">
              <el-select v-model="data.person_id" placeholder="请选择任务负责人" @change="personChange" clearable>
                <el-option
                  v-for="item in members"
                  :key="item.member_id"
                  :label="item.member_name"
                  :value="item.member_id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="任务参与人" prop="task_member_id">
              <template v-if="!data.isAdd">

                <div v-for="(item,index) in data.task_member" :key="index">

                  <span>{{item.member_name}}</span>

<!--                  <el-dropdown style="margin-left: 20px" @command="(command)=>{handleCommand(command,index)}">-->
<!--                  <span class="el-dropdown-link" style="color: #409EFF">-->
<!--                    更换<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
<!--                  </span>-->
<!--                    <el-dropdown-menu slot="dropdown">-->
<!--                      <el-dropdown-item v-for="(mem,idx) in getChangeMember()" :key="idx + item.member_id" :disabled="mem.disabled" :command="mem.member_id">{{mem.member_name}}</el-dropdown-item>-->

<!--                    </el-dropdown-menu>-->
<!--                  </el-dropdown>-->

                  <el-dropdown v-if="!item.is_add" style="margin-left: 20px" @command="(command)=>{handleCommand(command,index)}">
                  <span class="el-dropdown-link" style="color: #409EFF">
                    更换<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item v-for="(mem,idx) in getChangeMember()" :key="idx + item.member_id" :disabled="mem.disabled" :command="mem.member_id">{{mem.member_name}}</el-dropdown-item>

                    </el-dropdown-menu>
                  </el-dropdown>

                  <a v-else style="color: red;margin-left: 20px" @click="deleteMember(index)">删除</a>

                </div>

                <div>

                  <el-dropdown placement="bottom-start" @command="(command)=>{handleCommand2(command)}">
                  <span class="el-dropdown-link" style="color: #409EFF">
                    新增
                  </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item v-for="(mem,idx) in getChangeMember()" :key="idx" :disabled="mem.disabled" :command="mem.member_id">{{mem.member_name}}</el-dropdown-item>

                    </el-dropdown-menu>
                  </el-dropdown>

                </div>

              </template>

              <template v-else>
                <el-select
                  v-model="data.task_member_id"
                  @change="memberChange"
                  multiple
                  collapse-tags
                  placeholder="请选择">
                  <el-option
                    v-for="item in members"
                    :key="item.member_id"
                    :label="item.member_name"
                    :value="item.member_id">
                  </el-option>
                </el-select>
              </template>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="阶段性评审" prop="delivery" v-if="data.isAdd">
              <el-switch v-model="data.periodical_review"></el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="强制验收" prop="delivery" v-if="data.isAdd">
              <el-switch v-model="data.mandatory_check"></el-switch>
            </el-form-item>
          </el-col>

        </el-form>
      </el-row>


      <div class="document-view" v-if="data.isAdd">

        <div class="top" style="display: flex;justify-content: space-between;align-items: center">

          <p class="title">交付文档</p>

          <div class="btn-view" style="color: dodgerblue">

            <el-button size="medium" type="text" icon="el-icon-edit" @click="addClick">
              添加文档
            </el-button>

            <!--          <a class="dlt" @click="allDelete">全部删除</a>-->

          </div>

        </div>

        <el-table
          size="medium"
          :data="data.files"
          align="center"
          border
          style="width: 100%">
          <el-table-column
            prop="file_name"
            label="文档名称"
            width="200">
          </el-table-column>
          <el-table-column
            prop="type_name"
            label="文档类型"
            width="100">
          </el-table-column>
          <el-table-column
            label="申报所需文件"
            width="150">
            <template slot-scope="scope">
              <span>{{scope.row.need?'是':'否'}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="操作"
          >
            <template slot-scope="scope">

              <el-button size="medium" type="text" icon="el-icon-edit"  @click="editClick(scope.row,scope.$index)">
                编辑
              </el-button>
              <el-button class="text-btn-red" size="medium" type="text" icon="el-icon-delete" @click="deleteClick(scope.$index)">
                删除
              </el-button>
            </template>

          </el-table-column>
        </el-table>

      </div>


      <el-dialog
        title="文档"
        v-if="dialogVisible"
        :visible.sync="dialogVisible"
        width="500px"
        append-to-body
        :before-close="handleClose">

        <el-form ref="documentForm" :model="documentData" :rules="rules" class="demo-form-inline" label-width="100px" size="medium" label-position="left">
          <el-form-item label="文档名称" prop="file_name">
            <el-input v-model="documentData.file_name" placeholder="请输入文档名称" style="width: 100%" clearable></el-input>
          </el-form-item>
          <el-form-item label="文档类型" prop="file_type">
            <el-select v-model="documentData.file_type" placeholder="请选择文档类型" @change="typeChange" style="width: 100%" clearable>
              <el-option
                v-for="(item,index) in options"
                :key="index"
                :label="item.dict_val"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申报所需文件" prop="delivery">
            <el-switch v-model="documentData.need"></el-switch>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="documentConfirm">确 定</el-button>
        </span>
      </el-dialog>

    </div>
</template>

<script>
    export default {
        name: "editTaskView",
        props:{
            data:Object,
            documents:{
                type:Object,
                default:function () {
                    return{
                        list:[],
                        id:0,
                    }
                }
            },
            plans:{
                type:Array,
                default:function () {
                    return[]
                }
            },
            members:Array,
            project:Object,
        },
        watch:{
            project:{
                handler(newV){
                    if (newV && newV.plan_end_time){
                        this.endTime = newV.plan_end_time
                    }
                },
                immediate:true,
                deep:true
            }
        },
        data: function() {
            return {
                tableData:[],
                dialogVisible:false,
                documentData:{},
                rules: {
                    task_name: [
                        { required: true, message: '请输入名称', trigger: 'blur' }
                    ],
                    startDate: [
                        { required: true, message: '请选择开始日期', trigger: 'change' }
                    ],
                    endDate: [
                        { required: true, message: '请选择结束日期', trigger: 'change' }
                    ],
                    duration : [
                        { required: true, message: '请输入工期', trigger: 'blur' }
                    ],
                    person_id: [
                        { required: true, message: '请选择项目负责人', trigger: 'change' }
                    ],
                    task_member_id: [
                        { required: true, message: '请选择项目参与人', trigger: 'change' }
                    ],
                    file_name: [
                        { required: true, message: '请输入名称', trigger: 'blur' }
                    ],
                    file_type: [
                        { required: true, message: '请选择文档类型', trigger: 'change' }
                    ],
                },
                documentIndex:-1,
                planList:[],
                planList2:[],
                pickerOptions: {
                    disabledDate:time=> {
                        let bo = false
                        if (this.data.firstPlan && this.data.limitStart){
                            if (time.getTime() < new Date(this.data.limitStart).getTime()){
                                bo = true
                            }
                        }else{
                            if (time.getTime() < new Date().getTime()){
                                bo = true
                            }
                        }
                        if (this.endTime && time.getTime() > new Date(this.endTime).getTime()){
                            bo = true
                        }
                        return bo
                    }
                },
                pickerOptions2: {
                    disabledDate:time=> {
                        let bo = false
                        if (this.data.startDate != ''){
                            if (time.toLocaleDateString() == new Date(this.data.startDate).toLocaleDateString()){
                                bo = false
                            }else if (time.getTime() < new Date(this.data.startDate).getTime()){
                                bo = true
                            }
                        }else{
                            if (time.getTime() < new Date().getTime()){
                                bo = true
                            }
                        }
                        if (this.endTime && time.getTime() > new Date(this.endTime).getTime()){
                            bo = true
                        }
                        return bo
                    }
                },
                endTime:'',
                options: [],
            }
        },
        mounted:function(){
            this.options = this.$store.getters.sysDic('file_type')
            console.log(this.options)
            if (this.data.level > 1){
                let index = this.plans.findIndex(a=>a.id == this.data.parent_id)
                if (index != -1){
                    let parent = this.plans[index];
                    this.endTime = parent.end_date
                }
            }
        },
        methods:{
            validateFun:function(){
                return new Promise(((resolve, reject) => {
                    this.$refs.form.validate((valid) => {
                        if (valid){
                            resolve()
                        }else {
                            reject()
                        }
                    });
                }))

            },
            handleCommand2(command){
                let idx = this.members.findIndex(a=>a.member_id == command)
                if (idx != -1){
                    let mem = {...this.members[idx]}
                    mem.is_add = true
                    this.data.task_member.push(mem)

                }
            },
            handleCommand(command,index) {

                let idx = this.members.findIndex(a=>a.member_id == command)
                if (idx != -1){
                    let mem = {...this.members[idx]}
                    // this.datas.task_member[index] = mem;
                    this.$set(this.data.task_member,index,mem)

                }
                console.log(this.data.task_member)
            },
            deleteMember(index){
                this.data.task_member.splice(index,1)
            },
            getChangeMember:function(){
                let list = []
                for (let i = 0; i < this.members.length; i++){
                    let index = this.data.task_member.findIndex(a=>a.member_id == this.members[i].member_id)
                    let a = {...this.members[i]}
                    if (index != -1){
                        a.disabled = true;
                    }
                    list.push(a)
                }
                return list

            },
            startchange:function(time){
                console.log(time)
                if (this.data.startDate != ''){
                    this.data.startDate = this.dealDateStr(this.data.startDate)
                    this.data.start_date = this.data.startDate  + " 00:00:00"

                }
                if (this.data.duration){
                    this.data.endDate = this.dealDate(this.data.startDate,this.data.duration)
                    this.data.end_date = this.data.endDate + " 23:59:59"
                }else if (this.data.endDate){
                    let  startDate = Date.parse(this.data.startDate);
                    let  endDate = Date.parse(this.data.endDate);
                    if (startDate>endDate){
                        this.data.duration = 0;
                        this.data.endDate = ""
                        this.data.end_date = ""
                    }else if (startDate==endDate){
                        this.data.duration = 1
                    }else{
                        let num = ((endDate - startDate)/(1*24*60*60*1000)).toFixed(0)
                        this.data.duration = Number(num) + 1;

                    }
                }
            },
            endchange:function(){
                if (this.data.endDate){

                    this.data.endDate = this.dealDateStr(this.data.endDate)
                    this.data.end_date = this.data.endDate  + " 23:59:59"
                    // this.data.startDate = this.dealDate2(this.data.endDate,this.data.days)
                    // if (this.data.limitStart != ''){
                    //     if (new Date(this.data.startDate).getTime() < new Date(this.data.limitStart).getTime()){
                    //         this.data.startDate
                    //     }
                    // }

                    if (this.data.startDate){
                        let  startDate = Date.parse(this.data.startDate);
                        let  endDate = Date.parse(this.data.endDate);
                        if (startDate>endDate){
                            this.data.duration = 0;
                            this.data.endDate = ""
                            this.data.end_date = ""
                        }else if (startDate==endDate){
                            this.data.duration = 1
                        }else{
                            let num = ((endDate - startDate)/(1*24*60*60*1000)).toFixed(0)
                            this.data.duration = Number(num) + 1;
                        }
                    }else if (this.data.duration){
                        let a = this.dealStartDate(this.data.endDate,this.data.duration)  + " 00:00:00"
                        let date = new Date(a)
                        if (date.getTime() < new Date().getTime() && date.toLocaleDateString() != new Date().toLocaleDateString()){
                            return
                        }
                        this.data.startDate = a
                        this.data.start_date = this.data.startDate
                    }

                }
            },
            durationProving:function(val) {
                let str = this.data.duration
                // this.form.skus[e].Price 是input的值　　
                // 先把非数字的都替换掉，除了数字和.
                str = str.replace(/[^\d]/g, '');
                let num = Number(str)
                if (!num){
                    num = 1
                }

                this.data.duration = num;

            },
            blur:function(){
                if (this.data.startDate){

                    this.data.endDate = this.dealDate(this.data.startDate,this.data.duration)
                    this.data.end_date = this.data.endDate + " 23:59:59"
                }else if (this.data.endDate){
                    let a = this.dealStartDate(this.data.endDate,this.data.duration)
                    let date = new Date(a)
                    if (date.getTime() < new Date().getTime() && date.toLocaleDateString() != new Date().toLocaleDateString()){
                        return
                    }
                    this.data.startDate = a
                    this.data.start_date = this.data.startDate  + " 00:00:00"
                }
                // else if (this.data.endDate != ""){
                //     this.data.startDate = this.dealDate2(this.data.endDate,this.data.days)
                // }
            },
            dealStartDate:function(str,days){
                let date = new Date(str);
                if (days > 0){
                    days = days-1
                }
                let timeStr = Number(days) * 24 * 3600;
                if (date.getTime() > 99999999999){
                    timeStr = timeStr * 1000;
                }

                let dd = date.getTime() - timeStr

                let date2 = new Date(dd)

                return this.dealDateStr(date2)
            },
            dealDate:function(str,days){
                let date = new Date(str);
                if (days > 0){
                    days = days-1
                }

                let timeStr = Number(days) * 24 * 3600;
                if (date.getTime() > 99999999999){
                    timeStr = timeStr * 1000;
                }

                let dd = date.getTime() + timeStr

                let date2 = new Date(dd)

                return this.dealDateStr(date2)
            },
            dealDateStr:function(date){
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                let day = date.getDate();
                if (month < 10){
                    month = "0" + month
                }
                if (day < 10){
                    day = "0" + day;
                }

                return year + "-" + month + "-" + day
            },
            dealDate2:function(str,days){
                let date = new Date(str);

                let timeStr = Number(days) * 24 * 3600;
                if (date.getTime() > 99999999999){
                    timeStr = timeStr * 1000;
                }

                let dd = date.getTime() - timeStr

                let date2 = new Date(dd)

                let year = date2.getFullYear();
                let month = date2.getMonth() + 1;
                let day = date2.getDate();
                if (month < 10){
                    month = "0" + month
                }
                if (day < 10){
                    day = "0" + day;
                }

                return year + "-" + month + "-" + day
            },
            dealPlanList:function(list = null){
                this.planList = [];
                this.plans.forEach(item=>{
                    if (item.id != this.data.id && item.level != 5){
                        this.planList.push(item);
                    }
                })

                this.ids = [];
                if (list){
                    this.ids = this.ids.concat(list)
                }
                if (this.data.children && this.data.children.length > 0){
                    this.aaa(this.data.children);
                }

                this.planList2 = [];
                this.plans.forEach(item=>{
                    let index = this.ids.findIndex(a=>a == item.id)
                    if (item.id != this.data.id && index == -1){
                        this.planList2.push(item);
                    }
                })
            },
            aaa:function(list){
                for (let i = 0; i < list.length; i++){
                    if (list[i].children && list[i].children.length > 0){
                        this.aaa(list[i].children);
                    }
                    this.ids.push(list[i].id);
                }
            },
            allDelete:function(){
                this.data.files = [];
            },
            handleClose:function () {
                this.dialogVisible = false;
            },
            addClick:function () {
                this.dialogVisible = true;
                this.documentData = {
                    id:0,
                    file_name:'',
                    file_type:'',
                    type_name:'',
                    need:false,
                }
                this.documentIndex = -1;
            },
            documentConfirm:function () {
                if (this.$refs.documentForm){
                    this.$refs.documentForm.validate((valid) => {
                        if (valid){
                            let data = {...this.documentData};

                            if (this.documentIndex < 0){
                                data.id = this.documents.id + "";
                                this.documents.id ++;
                                this.data.files.push(data)
                            }else {
                                this.$set(this.data.files,this.documentIndex,data);
                            }
                            this.dialogVisible = false;
                        }
                    })
                }

            },
            formValidate:function(){

            },
            editClick:function (item,index) {
                this.documentData = {...item}
                this.documentIndex = index;
                this.dialogVisible = true;
            },
            deleteClick:function (index) {
                this.data.files.splice(index,1)
            },
            planChange:function (id) {

                let index = this.planList.findIndex(a=>a.id == id)
                if (index != -1){
                    let plan = this.planList[index]
                    this.data.parent_id = plan.id + "";
                    this.data.parent_name = plan.task_name;

                    this.endTime = plan.end_date
                }
            },
            preChange:function (id) {
                if (id){
                    let index = this.planList2.findIndex(a=>a.id == id)
                    if (index != -1){
                        let plan = this.planList2[index]
                        this.data.foreground_task_id = plan.id + "";
                        this.data.foreground_task_name = plan.task_name;
                    }
                }else{
                    this.data.foreground_task_id = "";
                    this.data.foreground_task_name = "";
                }

            },
            typeChange:function (id) {
                if (id){
                    let index = this.options.findIndex(a=>a.id == id)
                    if (index != -1){
                        let data = this.options[index];
                        this.documentData.file_type = data.id
                        this.documentData.type_name = data.dict_val
                    }
                }else{
                    this.documentData.file_type = ''
                    this.documentData.type_name = ''
                }

            },
            personChange:function (id) {
                if (!id){
                    this.data.person_id = ''
                    this.data.person_in_charge = {}
                    return
                }
                let index = this.members.findIndex(a=>a.member_id == id)
                if (index != -1){
                    let data = this.members[index];
                    this.data.person_id = data.member_id
                    this.data.person_in_charge = data

                    if (this.data.person_in_charge){
                        if (this.data.task_member){
                            let index1 = this.data.task_member.findIndex(a=>a.member_id == this.data.person_in_charge.member_id)
                            if (index1 != -1){
                                this.data.task_member.splice(index1,1)
                            }
                        }
                        if (this.data.task_member_id){
                            let index1 = this.data.task_member_id.findIndex(a=>a == this.data.person_in_charge.member_id)
                            if (index1 != -1){
                                this.data.task_member_id.splice(index1,1)
                            }
                        }
                    }
                    this.data.person_in_charge = data

                    if (!this.data.task_member){
                        this.data.task_member_id = [id]
                        this.data.task_member = [data]
                    }else{
                        let index1 = this.data.task_member.findIndex(a=>a.member_id == id)
                        if (index1 == -1){
                            this.data.task_member_id.push(id)
                            this.data.task_member.push(data)
                        }
                    }
                }

            },
            memberChange:function (mem) {
                this.data.task_member = [];
                this.data.task_member_id.forEach(id=>{
                    let index = this.members.findIndex(a=>a.member_id == id)
                    if (index != -1){
                        this.data.task_member.push(this.members[index])
                    }
                })
            }
        }
    }
</script>

<style lang="scss" scoped>
.change-task-edit-view{
  .el-form{
    .el-form-item__content{
      .el-input{
        width: 200px;
      }
      .el-select{
        width: 200px;
      }
    }
  }
}
</style>
